﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using Microsoft.Reporting.WinForms;
using Pharmacy;
using PrintReportSample;
using VCS.Data;
using VCS.Entities;
using VCS.Settings.BusinessLayer;
using VCS.Windows.Forms.Properties;
using WinUtilities.Class;
using WinUtilities.Form;

namespace VCS.Windows.Forms.Form.Main
{
    /// <summary>
    /// 
    /// </summary>
    public partial class FormPatientActivation : DevExpress.XtraEditors.XtraForm
    {
        /// <summary>
        /// 
        /// </summary>
        public Patient ObjPatient;

        /// <summary>
        /// 
        /// </summary>
        public bool mIsInsert = true;

        /// <summary>
        /// 
        /// </summary>
        public FormPatientActivation()
        {
            InitializeComponent();
            //Fill Data
            //Fill Data
            TList<Company> companies = DataRepository.CompanyProvider.GetAll();
            var countries = DataRepository.CountryProvider.GetAll();
            var memberTypes = DataRepository.MemberTypeProvider.GetAll();
            //companies.Insert(0, new Company { CompanyCode = null, CompanyName = "" });
            //Setup SearchLookUpEdit
            txtCompany.Properties.DataSource = companies;
            txtCompany.Properties.DisplayMember = "CompanyName";
            txtCompany.Properties.ValueMember = "CompanyCode";
            txtCompany.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;

            txtNationality.Properties.DataSource = countries;
            txtNationality.Properties.DisplayMember = "CitizenName";
            txtNationality.Properties.ValueMember = "CitizenName";
            txtNationality.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;

            txtMemberType.Properties.DataSource = memberTypes;
            txtMemberType.Properties.DisplayMember = "MemberType";
            txtMemberType.Properties.ValueMember = "MemberType";
            txtMemberType.KeyPress += GlobalUtilities.SearchLookUpEditFirstKeyPress;

            reportViewer1.LocalReport.EnableExternalImages = true;
            // Passing hotkey from Form to itemControlSearch
            //KeyPreview = true;
            //KeyPress += GlobalUtilities.FormKeyPress;
            //Lock Layout
        }

        /// <summary>
        /// 
        /// </summary>


        /// <summary>
        /// Get Data From Form
        /// </summary>
        /// <param name="objPatient"></param>
        public void LoadUpdate(Patient objPatient)
        {
            DataRepository.PatientProvider.DeepLoad(objPatient);
            txtFirstName.Text = objPatient.FirstName;
            txtLastName.Text = objPatient.LastName;
            txtMiddleName.Text = objPatient.MiddleName;
            txtNationality.EditValue = objPatient.Nationality;
            txtPatientCode.Text = objPatient.PatientCode;
            txtDOB.EditValue = objPatient.DateOfBirth;
            txtSex.SelectedItem = "Female";
            if (objPatient.Sex == "M")
                txtSex.SelectedItem = "Male";
            txtCompany.EditValue = objPatient.CompanyCode;
            txtNationality.Text = objPatient.Nationality;
            txtTelephone.Text = !string.IsNullOrEmpty(objPatient.MobilePhone) ? objPatient.MobilePhone : objPatient.HomePhone;
        }

        private void btn_Find_Click(object sender, System.EventArgs e)
        {
            string whereExpression = "";
            if (!string.IsNullOrEmpty(txtSPatientCode.Text))
                whereExpression += string.Format("PatientCode='{0}'", txtSPatientCode.Text);
            if (!string.IsNullOrEmpty(txtSLastName.Text))
            {
                if (whereExpression.Length > 0)
                    whereExpression += " AND ";
                whereExpression += string.Format("LastName LIKE '{0}%'", txtSLastName.Text);
            }
            if (!string.IsNullOrEmpty(txtSFirstName.Text))
            {
                if (whereExpression.Length > 0)
                    whereExpression += " AND ";
                whereExpression += string.Format("FirstName LIKE '{0}%'", txtSFirstName.Text);
            }
            int searchResultsCount;
            var searchResults = DataRepository.PatientProvider.GetPaged(whereExpression, "", 0, 100,
                                                                        out searchResultsCount);
            if (searchResults.Count > 0)
            {
                if (searchResults.Count == 1)
                {
                    DisplaySearchResult(searchResults[0]);
                }
                else
                {
                    var DisplayItems = new Collection<SearchItem>();
                    DisplayItems.Add(new SearchItem("Patient Code", "PatientCode", SearchItem.EnumFieldType.Text, 11));
                    DisplayItems.Add(new SearchItem("Last Name", "LastName", SearchItem.EnumFieldType.Text, 20));
                    DisplayItems.Add(new SearchItem("Fist Name", "FirstName", SearchItem.EnumFieldType.Text, 20));
                    var formSearchResult = new FormSearchResult { DisplayItems = DisplayItems };
                    formSearchResult.FillSearchResult(searchResults);
                    formSearchResult.DisplaySearchResult += DisplaySearchResult;
                    formSearchResult.ShowDialog();
                }
            }
            else
            {
                MessageBox.Show(Resources.SearchNotFound);
                txtSPatientCode.Focus();
            }
        }

        private void DisplaySearchResult(object resultRow)
        {
            ObjPatient = (Patient)resultRow;
            LoadUpdate(ObjPatient);
        }

        private void btn_Print_Click(object sender, System.EventArgs e)
        {
            if (ObjPatient == null)
            {
                MessageBox.Show(Resources.SelectPatient);
                txtSPatientCode.Focus();
            }
            else
            {
                var transactionCode = DateTime.Now.ToString("ddMMMyy").ToUpper() +
                                      ServiceFacade.SettingsHelper.LocationCode;
                var patientActivation = new PatientActivation();
                int count;
                TList<PatientActivation> listActivation =
                    DataRepository.PatientActivationProvider.GetPaged(
                        "TransactionID like '" + transactionCode + "' + '%'",
                        "TransactionID desc", 0, 1, out count);
                if (count == 0)
                    transactionCode += "001";
                else
                    transactionCode +=
                        String.Format("{0:000}",
                                      int.Parse(
                                          listActivation[0].TransactionId.Substring(
                                              listActivation[0].TransactionId.Length - 3)) + 1);

                patientActivation.TransactionId = transactionCode;
                patientActivation.PatientCode = ObjPatient.PatientCode;
                patientActivation.FirstName = ObjPatient.FirstName;
                patientActivation.LastName = ObjPatient.LastName;
                patientActivation.DateOfBirth = ObjPatient.DateOfBirth;
                patientActivation.Phone = string.IsNullOrEmpty(ObjPatient.MobilePhone)
                                              ? ObjPatient.MobilePhone
                                              : ObjPatient.HomePhone;
                patientActivation.Sex = ObjPatient.Sex;
                patientActivation.MemberType = ObjPatient.MemberType;
                patientActivation.MembershipSosNumber = ObjPatient.MembershipSosNumber;
                patientActivation.MembershipSosExpDate = ObjPatient.MembershipSosExpDate;
                patientActivation.InsuranceCardNumber = ObjPatient.InsuranceCardNumber;
                patientActivation.InsuranceCardExpDate = ObjPatient.InsuranceCardExpDate;
                patientActivation.CompanyCode = ObjPatient.CompanyCode;
                if (ObjPatient.CompanyCodeSource != null)
                    patientActivation.CompanyName = ObjPatient.CompanyCodeSource.CompanyName;
                patientActivation.Nationality = ObjPatient.Nationality;
                patientActivation.ApptRemark = ObjPatient.ApptRemark;
                int? result = 0;
                string note = "";
                string id = "";
                DataRepository.PatientActivationProvider.Activation(ObjPatient.PatientCode, "Confirmed", Program.GlobalUser.UserId, ref result, ref id, ref note);
                patientActivation.ApptStatus = result == 1 ? "Have appointment" : "Not have appointment";
                patientActivation.ApptNote = note;
                patientActivation.Remark = ObjPatient.Remark;
                patientActivation.Status = "Open";
                patientActivation.IsComplete = false;
                patientActivation.CreateDate = DateTime.Now;
                patientActivation.CreateUser = Program.GlobalUser.UserId;
                DataRepository.PatientActivationProvider.Insert(patientActivation);
                var fullAppPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                var patientCodePath = Path.Combine(fullAppPath, "PatientCode.png");
                var transactionCodePath = Path.Combine(fullAppPath, "TransactionID.png");
                GlobalUtilities.CreateBarCode(patientActivation.PatientCode, patientCodePath);
                GlobalUtilities.CreateBarCode(patientActivation.TransactionId, transactionCodePath);

                var listParameters = new Collection<ReportParameter>();
                listParameters.Add(new ReportParameter("TransactionCodePath", transactionCodePath));
                listParameters.Add(new ReportParameter("PatientCodePath", patientCodePath));
                reportViewer1.LocalReport.SetParameters(listParameters);
                reportViewer1.LocalReport.DataSources.Clear();
                var dsPatientActivation = new List<PatientActivation>();
                dsPatientActivation.Add(patientActivation);
                reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("PatientActivation_PatientActivation",
                                                                               dsPatientActivation));
                reportViewer1.RefreshReport();
                var printDoc = new ReportPrintDocument(reportViewer1.LocalReport);
                printDoc.Print();
                ObjPatient = null;
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (GlobalUtilities.GlobalProcessCmdKey(this, FormHotKey, ref msg, keyData))
                return true;
            return base.ProcessCmdKey(ref msg, keyData);
        }

        protected bool FormHotKey(Keys keyData)
        {
            if (keyData == Keys.F4)
            {
                btn_Find_Click(btn_Find, null);
                return true;
            }
            if (keyData == Keys.F5)
            {
                btn_Print_Click(btn_Print, null);
                return true;
            }
            return false;
        }
    }
}